using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace DIS_App_Client.MainManagers
{
	#region using
	using DIS_App_Client.Helpers;
	using System.Data;
	using System.Drawing;
	using System.IO;
	using DIS_App_Client.DIS_WS_BusinessLayer;
	#endregion
	public partial class FrmManageEmployee : Form
	{
		private System.Windows.Forms.TextBox txtIDRole;
		private System.Windows.Forms.TextBox txtIDChemistWareHouse;

		public FrmManageEmployee(bool enableChon = false)
		{
			InitializeComponent();
		}

		private void FrmManageEmployee_Load(object sender, EventArgs e)
		{
			InitGridView();
			InitHiddenFields();

            // Load list of users belong to selected role
            LoadData();
            LoadRole();
			dtgvData.ClearSelection();
		}

        public void LoadRole()
        {
            // The first user start application
            if (GlobalVariables.g_CurrentUser == null)
            {
                txtIDRole.Text = "1";
                txtRole.Text = "National Manager";
                lblManageName.Text = "NATIONAL MANAGER";
                grpListData.Text = "List of National Manager";
                btnSelectChemistWareHouse.Enabled = false;
            }
            else
            {
                if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.NATIONAL)
                {
                    txtIDRole.Text = "2";
                    txtRole.Text = "Local Manager";
                    lblManageName.Text = "LOCAL MANAGER";
                    grpListData.Text = "List of Local Manager";
                }
                else if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.LOCAL)
                {
                    txtIDRole.Text = "3";
                    txtRole.Text = "Staff";
                    lblManageName.Text = "STAFF";
                    grpListData.Text = "List of Staff";
                    btnSelectChemistWareHouse.Enabled = false;
                    btnSelectRole.Enabled = false;
                    btnSelectChemistWareHouse.Enabled = false;
                    txtIDChemistWareHouse.Text = GlobalVariables.g_CurrentUser.IDChemistWareHouse.ToString();
                    txtChemistWareHouse.Text = GlobalVariables.g_CurrentUser.ChemistWareHouse.Name.ToString();
                }
            }
        }

		private void btnAdd_Click(object sender, EventArgs e)
		{
			var errorText = "";
			if (!ValidateInput(EnumUpdateMode.INSERT, ref errorText))
			{
				MessageBox.Show(errorText, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			if (ActionAdd())
			{
                MessageBox.Show(CommonHelper.GetMessage("Insert", "Successful"), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (GlobalVariables.g_CurrentUser == null)
                {
                    MessageBox.Show("The national manager has been created.\nThe application will be exited to configure system!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Application.Exit();
                }
				LoadData();
				btnReset_Click(sender, e);
			}
			else
			{
                MessageBox.Show(CommonHelper.GetMessage("Insert", "Fail"), "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			var errorText = "";
			if (!ValidateInput(EnumUpdateMode.DELETE, ref errorText))
			{
				MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
            if (MessageBox.Show(CommonHelper.GetMessage("Delete", "Confirm"), "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				if (ActionDelete())
				{
                    MessageBox.Show(CommonHelper.GetMessage("Delete", "Successful"), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
					LoadData();
					btnReset_Click(sender, e);
				}
				else
				{
                    MessageBox.Show(CommonHelper.GetMessage("Delete", "Fail"), "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}

		private void btnUpdate_Click(object sender, EventArgs e)
		{
			var errorText = "";
			if (!ValidateInput(EnumUpdateMode.UPDATE, ref errorText))
			{
				MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			if (ActionUpdate())
			{
                MessageBox.Show(CommonHelper.GetMessage("Update", "Successful"), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
				LoadData();
			}
			else
			{
                MessageBox.Show(CommonHelper.GetMessage("Update", "Fail"), "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void btnExit_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void btnReset_Click(object sender, EventArgs e)
		{
			txtID.Text = "";
            if (GlobalVariables.g_CurrentUser.Role.Name.Trim() != "Local Manager")
            {
                txtIDChemistWareHouse.Text = "";
                txtChemistWareHouse.Text = "";
            }
			txtUserName.Text = "";
			txtFullName.Text = "";
            if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.NATIONAL)
            {
                btnSelectRole.Enabled = true;
                btnSelectChemistWareHouse.Enabled = true;
            }
		}

		private void dtgvData_CellClick(object sender, DataGridViewCellEventArgs e)
		{
			if (dtgvData.SelectedRows == null || dtgvData.SelectedRows.Count == 0)
				return;
			var selectedItem = dtgvData.SelectedRows[0];
			txtID.Text = dtgvData.SelectedRows[0].Cells["ID"].Value.ToString();
			var item = BusService.Instance.Employee_SelectByID(int.Parse(txtID.Text));

			LoadDetailInfo(item);

            btnSelectRole.Enabled = false;
            if (dtgvData.SelectedRows[0].Cells["Role"].Value.ToString().ToUpper().Contains("INTERNET") ||
                dtgvData.SelectedRows[0].Cells["Role"].Value.ToString().ToUpper().Contains("STAFF"))
            {
                btnSelectChemistWareHouse.Enabled = false;
            }
            else
            {
                btnSelectChemistWareHouse.Enabled = true;
            }
		}

		public void LoadDetailInfo(EmployeeDTO item)
		{
			txtIDRole.Text = item.IDRole == -1 ? "" : item.IDRole.ToString();
			txtRole.Text = item.Role == null ? "" : item.Role.Name.ToString();
			txtIDChemistWareHouse.Text = item.IDChemistWareHouse == -1 ? "" : item.IDChemistWareHouse.ToString();
			txtChemistWareHouse.Text = item.ChemistWareHouse == null ? "" : item.ChemistWareHouse.Name.ToString();
			txtUserName.Text = item.UserName == null ? "" : item.UserName.ToString();
			txtFullName.Text = item.FullName == null ? "" : item.FullName.ToString();
		}

		private void InitGridView()
		{
			DataGridViewTextBoxColumn objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "ID",
				DataPropertyName = "ID",
				Name = "ID",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/5))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "Role",
				DataPropertyName = "Role",
				Name = "Role",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/5))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "ChemistWareHouse",
				DataPropertyName = "ChemistWareHouse",
				Name = "ChemistWareHouse",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/5))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "UserName",
				DataPropertyName = "UserName",
				Name = "UserName",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/5))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "FullName",
				DataPropertyName = "FullName",
				Name = "FullName",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/5)) - 1
			};
			dtgvData.Columns.Add(objColumn);
		}

		public void InitHiddenFields()
		{
			txtIDRole = new System.Windows.Forms.TextBox
			{
				Name = "txtIDRole",
				Text = ""
			};
			txtIDRole.Visible = false;
			txtIDChemistWareHouse = new System.Windows.Forms.TextBox
			{
				Name = "txtIDChemistWareHouse",
				Text = ""
			};
			txtIDChemistWareHouse.Visible = false;
		}

		private void LoadData()
		{
            var idRole = -1;
            var dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("Role");
            dt.Columns.Add("ChemistWareHouse");
            dt.Columns.Add("UserName");
            dt.Columns.Add("FullName");

            // The first user start application
            if (GlobalVariables.g_CurrentUser == null)
            {
                idRole = 1;
            }
            else
            {
                if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.NATIONAL)
                {
                    idRole = 2;
                }
                else if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.LOCAL)
                {
                    idRole = 3;
                }
            }

            var lstItem = BusService.Instance.Employee_SelectByIDRole(idRole).ToList();
            if (idRole == 2)
            {
                var lst2 = BusService.Instance.Employee_SelectByIDRole(4).ToList();//Intenet manager
                lstItem = lstItem.Union(lst2).ToList();
            }
            for (int i = 0; i < lstItem.Count; i++)
            {
                dt.Rows.Add(lstItem[i].ID, lstItem[i].IDRole == -1 ? "" : lstItem[i].Role.Name, lstItem[i].IDChemistWareHouse == -1 ? "" : lstItem[i].ChemistWareHouse.Name, lstItem[i].UserName, lstItem[i].FullName);
            }
			DataView objTimeSheetDV = new System.Data.DataView(dt);
			objTimeSheetDV.AllowNew = false;
			dtgvData.AutoGenerateColumns = false;
			dtgvData.DataSource = objTimeSheetDV;
			dtgvData.ClearSelection();
		}

		private bool ValidateInput(EnumUpdateMode mode, ref string errorText)
		{
			if (mode == EnumUpdateMode.UPDATE || mode == EnumUpdateMode.DELETE)
			{
				if (txtID.Text.Equals(string.Empty))
				{
					errorText = "Please choose ID";
					return false;
				}
			}
			if (mode != EnumUpdateMode.DELETE)
			{
                if (GlobalVariables.g_CurrentUser != null)
                {
                    if (txtIDChemistWareHouse.Text.Equals(string.Empty))
                    {
                        errorText = "Please select ChemistWareHouse";
                        return false;
                    }
                }
                if (txtUserName.Text.Equals(string.Empty))
				{
					errorText = "Please enter UserName";
					return false;
				}
                var lstEmployee = BusService.Instance.Employee_SelectAll().ToList();
                if (lstEmployee.Any(n => n.UserName.Equals(txtUserName.Text.Trim())))
                {
                    errorText = "UserName is existent, please enter other username";
                    return false;
                }
			}
			return true;
		}

		private bool ActionAdd()
		{
			try
			{
				var item = new EmployeeDTO
				{
					IDRole = int.Parse(txtIDRole.Text),
					UserName = txtUserName.Text,
					Password = Encryption.Encrypt("123"),
					FullName = txtFullName.Text,
				};
                if (!(string.Empty).Equals(txtIDChemistWareHouse.Text))
                {
                    item.IDChemistWareHouse = int.Parse(txtIDChemistWareHouse.Text);
                }
				if (!BusService.Instance.Employee_Insert(item))
				{
					return false;
				}
				return true;
			}
			catch
			{
				return false;
			}
		}

		private bool ActionUpdate()
		{
			try
			{
				var item = BusService.Instance.Employee_SelectByID(int.Parse(txtID.Text));
				item.IDRole = int.Parse(txtIDRole.Text);
				item.UserName = txtUserName.Text;
				item.FullName = txtFullName.Text;
                if (!(string.Empty).Equals(txtIDChemistWareHouse.Text))
                {
                    item.IDChemistWareHouse = int.Parse(txtIDChemistWareHouse.Text);
                }
				return BusService.Instance.Employee_Update(item);
			}
			catch
			{
				return false;
			}
		}

		private bool ActionDelete()
		{
			try
			{
				return BusService.Instance.Employee_Delete(int.Parse(txtID.Text));
			}
			catch
			{
				return false;
			}
		}

		private void btnSelectChemistWareHouse_Click(object sender, EventArgs e)
		{
			FrmManageChemistWareHouse frm = new FrmManageChemistWareHouse(true);
			frm.Handler += GetChemistWareHouse;
			frm.ShowDialog();
		}

		public void GetChemistWareHouse(object sender, EventArgs e)
		{
			var eventType = (TransferSimpleDataEvent)e;
			string[] comp = eventType.Data.Split(new char[] { '#' });
			txtIDChemistWareHouse.Text = comp[0];
			txtChemistWareHouse.Text = comp[1];
		}

        private void btnSelectRole_Click(object sender, EventArgs e)
        {
            FrmSelectRole frm = new FrmSelectRole();
            frm.Handler += GetRole;
            frm.ShowDialog();
        }

        private void GetRole(object sender, EventArgs e)
        {
            TransferSimpleDataEvent transferData = (TransferSimpleDataEvent)e;
            var role = BusService.Instance.Role_SelectByID(int.Parse(transferData.Data));
            txtIDRole.Text = role.ID.ToString();
            txtRole.Text = role.Name;
            // Selected Role is "Internet Manager"
            if (role.Name.ToUpper().Contains("INTERNET"))
            {
                // Select Online Warehouse
                var onlineWareHouse = BusService.Instance.ChemistWareHouse_SelectAll().First(n => n.Name.ToUpper().Contains("ONLINE"));
                if (onlineWareHouse == null)
                {
                    onlineWareHouse = new ChemistWareHouseDTO
                    {
                        Name = "Online WareHouse",
                        Phone = string.Empty,
                        Address = string.Empty
                    };
                    var result = BusService.Instance.ChemistWareHouse_Insert(onlineWareHouse);
                    if (result)
                    {
                        var lst = BusService.Instance.ChemistWareHouse_SelectAll();
                        onlineWareHouse = BusService.Instance.ChemistWareHouse_SelectAll().First(n => n.Name.Contains("ONLINE"));
                    }
                }
                btnSelectChemistWareHouse.Enabled = false;
                txtIDChemistWareHouse.Text = onlineWareHouse.ID.ToString();
                txtChemistWareHouse.Text = onlineWareHouse.Name;
            }
            else
            {
                btnSelectChemistWareHouse.Enabled = true;
                txtIDChemistWareHouse.Text = string.Empty;
                txtChemistWareHouse.Text = string.Empty;
            }
        }
	}
}